package com.xwder.nio.selector;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.nio.charset.StandardCharsets;

/**
 * Selector SelectionKey demo client端
 *
 * @author xwder
 * @date 2021/3/17 21:34
 */
public class NioClient {

    private final static Logger logger = LoggerFactory.getLogger(NioClient.class);

    public static void main(String[] args) throws Exception{
        // 获取网络通道
        SocketChannel socketChannel = SocketChannel.open();
        // 设置非阻塞
        socketChannel.configureBlocking(false);
        // 提供服务器的ip和端口
        InetSocketAddress inetSocketAddress = new InetSocketAddress("127.0.0.1", 6666);
        // 连接服务器 非阻塞方式连接
        if (!socketChannel.connect(inetSocketAddress)) {
            while (!socketChannel.finishConnect()){
                logger.info("客户端连接需要时间，客户端不会阻塞，可以做其他的工作");
            }
        }
        logger.info("客户端连接成功~~~");
        String str  = "hello NioServer ~~~";
        // wrap a byte array into buffer
        ByteBuffer byteBuffer = ByteBuffer.wrap(str.getBytes(StandardCharsets.UTF_8));
        // 发送数据将buffer数据写入channel
        socketChannel.write(byteBuffer);

        // 保持连接
        System.in.read();
    }
}
